package com.sixiaolong.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sixiaolong.common.BaseContext;
import com.sixiaolong.common.R;
import com.sixiaolong.domain.AddressBook;
import com.sixiaolong.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

//    获取地址
    @GetMapping("/list")
    public R<List<AddressBook>> getAllAddress(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);
    }

//    新增
    @PostMapping
    public R<AddressBook> saveAddress(@RequestBody AddressBook addressBook){
//        获取TreadLocal  存的id
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

//    设置默认地址
    @PutMapping("/default")
    @Transactional
    public R<AddressBook> defaultAddress(@RequestBody AddressBook addressBook){
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lqw.set(AddressBook::getIsDefault,0);
        addressBookService.update(lqw);
//        先把根据userid查的全部设置为普通的地址   之后把前台传的根据地址id查的设置为默认地址
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

//    获取默认地址
    @GetMapping("/default")
    public R<AddressBook> getDefaultAddress(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lqw.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(lqw);
        return R.success(addressBook);
    }
}
